package com.atguigu.demo1;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo{
    public static void main(String[] args) {
        Ticket t = new Ticket();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 51; i++) {
                    t.sale();
                }
            }
        }, "窗口1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 51; i++) {
                    t.sale();
                }
            }
        }, "窗口2");
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 51; i++) {
                    t.sale();
                }
            }
        }, "窗口3");
        t1.start();
        t2.start();
        t3.start();
    }

}

class Ticket{
    private int ticket = 50;

    Lock lock = new ReentrantLock(true);
    public void sale(){
        lock.lock();
             try {
                 if (ticket > 0) {
                     String name = Thread.currentThread().getName();
                     System.out.println(name + "正在卖第" + ticket-- + "张票");
                 }
             } finally {
               lock.unlock();
             }
    }

   /* @Override
    public void run() {
        while(ticket > 0){
            synchronized (this) {
//                try {
//                    Thread.sleep(5);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                if (ticket > 0) {
                    String name = Thread.currentThread().getName();
                    System.out.println(name + "正在卖第" + ticket-- + "张票");
                }
            }

            //一个窗口完了之后休息一会，方便别的窗口进行（因为一个窗口完了之后，不休息，它会比别的窗口有更高的优先级）
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }*/
}
